import json
import pickle
import base64
from django.http import JsonResponse
from django.views import View
from django.shortcuts import render
# Create your views here.
from django_redis import get_redis_connection
from apps.goods.models import SKU



class CartsView(View):

    def post(self, request):
        """添加购物车"""
        # 接收和校验参数
        # 判断用户是否登录
        data = json.loads(request.body.decode())
        sku_id=data.get('sku_id')
        count = data.get('count')
        try:
            sku= SKU.objects.get(id= sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code':400,'errmsg':'查无此商品'})

        try:
            count= int(count)
        except Exception:
            count= 1
        user = request.user
        # 用户已登录，操作redis购物车
        if user.is_authenticated:
            redis_cli= get_redis_connection('carts')
            redis_cli.hset('carts_%s'%user.id,sku_id,count)
            redis_cli.sadd('selected_%s'%user.id,sku_id)

            return JsonResponse({'code':0,'errmsg':'ok'})

        else:
            # 用户未登录，操作cookie购物车
            cookie_carts= request.COOKIES.get('carts')
            if cookie_carts:
                carts= pickle.loads(base64.b64decode(cookie_carts))
            else:

                carts= {}

            if sku_id in carts:
                origin_count = carts[sku_id]['count']
                count += origin_count

            #     carts[sku_id] = {
            #         'count': count,
            #         'selected': True
            #     }
            # else:
            carts[sku_id]= {
                'count':count,
                'selected':True
            }
            carts_bytes= pickle.dumps(carts)
            base64encode= base64.b64encode(carts_bytes)

            response= JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('carts',base64encode.decode(),max_age=3600*24*14)
            return response

    def get(self,request):
        user= request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            sku_id_counts = redis_cli.hgetall('carts_%s'%user.id)
            selected_ids = redis_cli.smembers('selected_%s'%user.id)
            carts = {}
            for sku_id,count in sku_id_counts.items():
                carts[int(sku_id)] = {
                    'count':int(count),
                    'selected':sku_id in selected_ids
                }
        else:
            cookie_carts = request.COOKIES.get('carts')
            if cookie_carts is not None:
                carts = pickle.loads(base64.b64decode(cookie_carts))
            else:
                carts = {}

        sku_ids = carts.keys()
        skus = SKU.objects.filter(id__in = sku_ids)
        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'price': sku.price,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'selected': carts[sku.id]['selected'],
                'count': int(carts[sku.id]['count']),
                'amount': sku.price*carts[sku.id]['count']
            })
        return JsonResponse({'code':0,'errmsg': 'ok','cart_skus': sku_list})

    def put(self,request):
        user = request.user

        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected')

        if not all([sku_id,count]):
            return JsonResponse({'code':400,'errmsg':'参数不全'})
        try:
            SKU.objects.get(id = sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此商品'})
        try:
            count = int(count)
        except Exception:
            count =1

        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_cli = get_redis_connection('carts')
            redis_cli.hset('carts_%s'%user.id,sku_id,count)
            if selected:
                redis_cli.sadd('selected_%s'%user.id,sku_id)
            else:
                redis_cli.srem('selected_%s'%user.id,sku_id)
            return JsonResponse({'code':0,'errmsg':'ok','cart_sku':{'count':count,'selected':selected}})

        else:
            # 用户未登录，修改cookie购物车
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart is not None:
                carts = pickle.loads(base64.b64decode(cookie_cart))
            else:
                carts = {}
            if sku_id in carts:
                carts[sku_id] = {
                    'count':count,
                    'selected':selected
                }

            new_carts = base64.b64encode(pickle.dumps(carts))
            response = JsonResponse({'code':0,'errmsg':'ok','cart_sku':{'count':count,'selected':selected}})
            response.set_cookie('carts',new_carts.decode(),max_age=14*24*3600)
            return response

    def delete(self,request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        try:
            SKU.objects.get(pk=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'{code':400,'errmsg':'没有此商品'})

        user = request.user
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            redis_cli.hdel('carts_%s'%user.id,sku_id)
            redis_cli.srem('selected_%s'%user.id,sku_id)
            return JsonResponse({'code':0,'errmsg':'ok'})
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart is not None:
                carts = pickle.loads(base64.b64decode(cookie_cart))
            else:
                carts={}
            del carts[sku_id]
            new_carts= base64.b64encode(pickle.dumps(carts))
            response = JsonResponse({'code':0,'errmsg':'ok'})
            response.set_cookie('carts',new_carts.decode(),max_age=14*24*3600)
            return response


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收和校验参数
        data = json.loads(request.body.decode())
        selected = data.get('selected',True)
        if selected:
            if not isinstance(selected,bool):
                return JsonResponse({'code':400,'errmsg':'参数selected有误'})
        # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_cli = get_redis_connection('carts')
            cart = redis_cli.hgetall('carts_%s' % user.id)
            sku_ids = cart.keys()
            if selected:
                redis_cli.sadd('selected_%s'%user.id, *sku_ids)
            else:
                redis_cli.srem('selected_%s'%user.id, *sku_ids)
            return JsonResponse({'code': 0, 'errmsg': 'ok'})
        else:
            # 用户未登录，操作cookie购物车
            cart = request.COOKIES.get('carts')
            response = JsonResponse({'code': 0, 'errmsg': '全选购物车成功'})
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
                for sku_id in cart:
                    cart[sku_id]['selected'] = selected
                cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
                response.set_cookie('carts', cookie_cart, max_age=7 * 24 * 3600)

            return response


class CartsSimpleView(View):
    """商品页面右上角购物车"""

    def get(self, request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询Redis购物车
            redis_cli = get_redis_connection('carts')
            redis_cart = redis_cli.hgetall('carts_%s' % user.id)
            cart_selected = redis_cli.smembers('selected_%s' % user.id)
            # 将redis中的两个数据统一格式，跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image.url
            })

        # 响应json列表数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_skus': cart_skus})








